<template>
  <div class="loGin">
    <!-- 头部 
      "$router.go(-1)" 返回上一页-->
    <div class="nav">
      <van-nav-bar
        title="登录"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
      />
    </div>
    <!-- Field 输入框 -->
    <div class="field">
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field
            v-model="mobile"
            required
            name="mobile"
            label="手机号"
            type="tel"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请填写手机号' },
              {
                pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                message: '手机号格式不对'
              }
            ]"
          />
          <van-field
            v-model="code"
            required
            name="code"
            label="验证码"
            type="tel"
            placeholder="请输入验证码"
            :rules="[
              { required: true, message: '验证码没有写哦!' },
              { pattern: /\d{6}/, message: '验证码格式不对' }
            ]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button
            round
            block
            :loading="isLoading"
            :disabled="isLoading"
            type="info"
            loading-text="登录中..."
            native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
//导入网络中间层
import { userLogin } from '@/views/user/user.js'
//导入token方法
import { setToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      // 送axios之前加载loading
      this.isLoading = true
      console.log('submit', values)
      //发送登录请求   将数据传参利用中间层请求
      userLogin(values.mobile, values.code)
        .then(res => {
          //成功执行
          console.log(res)
          this.$toast.success('登录成功')
          //保存token
          setToken(res.data.data)
          //跳转首页
          this.$router.push({ path: '/home' })
        })
        .catch(err => {
          //失败执行
          this.$toast.fail('手机号或密码错误')
        })
        .then(res => {
          //不论失败还是成功都会执行
          this.isLoading = false
        })
    }
  }
}
</script>

<style></style>
